package com.dmgis.qxfw.dao;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.dmgis.qxfw.common.DbConfig;


@Repository
public class ProcessRequestDaoImpl implements ProcessRequestDaoI {

	@Deprecated
	@Override
	public <T> List<T> getData(String sql, String dbName,String userName,String pwd ,Class<T> clazz) throws Exception {
		Connection con = null;
		Statement stmt = null;
		List<T> list = new ArrayList<T>();
		Class.forName("org.postgresql.Driver");
		con = DriverManager.getConnection(DbConfig.pg_url+dbName,
	            userName, pwd);
		stmt = con.createStatement();
		ResultSet rs = stmt.executeQuery(sql);
		list = resultToList(rs,clazz);
		con.close();
		stmt.close();
		rs.close();
		return list;
	}
	
	@Deprecated
	public static <T> List<T> resultToList(ResultSet resultSet, Class<T> clazz) {
		List<T> list = new ArrayList<>();
        try {
            
            //获取resultSet 的列的信息
            ResultSetMetaData metaData = resultSet.getMetaData();
            //遍历resultSet
            //如果结果集为空
            if(resultSet.wasNull()){
            	return list;
            }else{
            	while(resultSet.next()){
            	  //通过反射获取对象的实例
                  T t = clazz.getConstructor().newInstance();
          		  //遍历每一列
                  for (int i = 0; i < metaData.getColumnCount(); i++) {
                      //获取列的名字
                      String fName = metaData.getColumnLabel(i + 1);
                      //列的名字和实体中的属性名是一样的，通过列的名字获得实体中属性
                      Field field = clazz.getDeclaredField(fName.toLowerCase());
                      //获得其对应的set方法
                      String setName = "set" + fName.toUpperCase().substring(0, 1) + fName.substring(1).toLowerCase();
                      //因为属性的类型和set方法的参数类型一致，所以可以获得set方法
                      Method setMethod = clazz.getMethod(setName, field.getType());
                      //把resultSet中的值传入实体中
                      try {
                    	  field.setAccessible(true);
                    	  if(resultSet.getObject(fName)!=null){
                    		  //float和double转换
                    		  if(resultSet.getObject(fName).getClass().equals(Double.class)&&
                    				  field.getGenericType().equals(Float.class)){
                    			  setMethod.invoke(t, Float.valueOf(String.valueOf(resultSet.getObject(fName))));
                    			  continue;
                    		  }else{
                    			  setMethod.invoke(t, resultSet.getObject(fName));
                    		  }
                    	  }else{
                    		  continue;
                    	  }
                    	  
					} catch (Exception e) {
						e.printStackTrace();
						System.err.println("错误属性："+fName+"    值："+resultSet.getObject(fName)
									+"   值类型："+resultSet.getObject(fName).getClass().getName()
									+"   实体类："+clazz);
					}
                  }
                  //把赋值后的对象 加入到list集合中
                  list.add(t);
//                  System.out.println(t);
            	}
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 返回list
        return list;
	}
	
	//查询数据
	public List<Map<String, Object>> selectData(String sql, String dbName,String userName,String pwd) throws Exception{
		MyResultSetHandle setHandle = new MyResultSetHandle();
		Connection con = null;
		Statement stmt = null;
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
		Class.forName("org.postgresql.Driver");
		con = DriverManager.getConnection(DbConfig.pg_url+dbName,
	            userName, pwd);

			stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			//处理数据集，转为map<String,Object>数据返回
			list = setHandle.resultToList(rs);
			rs.close();
		}catch (Exception e){}
		finally {
			if (stmt != null && !stmt.isClosed())
				stmt.close();
			if (con != null && !con.isClosed())
				con.close();
		}
		return list;
	}


	//删除
	@Override
	public String delData(String sql, String dbName, String userName, String pwd) throws Exception {
		Connection con = null;
		PreparedStatement smt = null;
		Class.forName("org.postgresql.Driver");
		String delResult = "";
		try {
			con = DriverManager.getConnection(DbConfig.pg_url + dbName, userName, pwd);
			smt = con.prepareStatement(sql);
			int i = smt.executeUpdate();
			delResult = String.valueOf(i);
		} catch (Exception e) {
		} finally {
			if (con != null && !con.isClosed())
				con.close();
		}
		return delResult;
	}

	//更新
	@Override
	public String updateData(String sql, String dbName, String userName, String pwd) throws Exception {
		System.err.println(sql);
		Connection con = null;
		PreparedStatement smt = null;
		int i = 0;
		try {
			Class.forName("org.postgresql.Driver");
			con = DriverManager.getConnection(DbConfig.pg_url + dbName, userName, pwd);
			smt = con.prepareStatement(sql);
			i = smt.executeUpdate();
		} catch (Exception e) {
		} finally {
			if (con != null && !con.isClosed())
				con.close();
		}
		String str = String.valueOf(i);
		return str;
	}

	//插入
	@Override
	public String insertData(String sql, String dbName, String userName, String pwd) throws Exception {
		System.out.println(sql);
		Connection con = null;
		PreparedStatement smt = null;
		int i=0;
		try {
			Class.forName("org.postgresql.Driver");
			con = DriverManager.getConnection(DbConfig.pg_url, userName, pwd);
			smt = con.prepareStatement(sql);
			i = smt.executeUpdate();
		}catch (Exception e) {
		} finally {
			if (con != null && !con.isClosed())
				con.close();
		}
		String insertResult = String.valueOf(i);
		return insertResult;
	}
}
